<?php

namespace app\admin\controller;

use app\common\controller\Backend;
use app\common\model\card\Dealer;
use app\common\model\Merchant;
use app\common\model\Order;
use app\common\model\Washlog;
use Exception;
use think\Db;
use think\exception\DbException;
use think\response\Json;

/**
 * 提现管理
 *
 * @icon fa fa-circle-o
 */
class Withdrawal extends Backend
{

    /**
     * Withdrawal模型对象
     * @var \app\common\model\Withdrawal
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\common\model\Withdrawal;
        $this->view->assign("sourceDataList", $this->model->getSourceDataList());
        $this->view->assign("typeDataList", $this->model->getTypeDataList());
        $this->view->assign("statusList", $this->model->getStatusList());
    }


    /**
     * 查看
     *
     * @return string|Json
     * @throws \think\Exception
     * @throws DbException
     */
    public function index()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if (false === $this->request->isAjax()) {
            return $this->view->fetch();
        }
        //如果发送的来源是 Selectpage，则转发到 Selectpage
        if ($this->request->request('keyField')) {
            return $this->selectpage();
        }
        $filter = $this->request->request("filter");
        $filter = json_decode($filter, true);
        if (!isset($filter["source_data"])) {
            $op = $this->request->request("op");
            $op = json_decode($op, true);
            $filter["source_data"] = 1;
            $op["source_data"] = '=';
            $this->request->get(['filter' => json_encode($filter), "op" => json_encode($op)]);
        }
        [$where, $sort, $order, $offset, $limit] = $this->buildparams();
        $list = $this->model;
        $source_data = 1;//来源:1=店铺,2=区域服务商,3=卡经销商,4=分销商
        if (empty($filter) || (isset($filter["source_data"]) && $filter["source_data"] == 1)) {
            //店铺
            $list = $list->with(["merchant" => function ($query) {
                $query->withField('id,name');
            }]);
        }
        if (!empty($filter)) {
            $source_data = $filter["source_data"];
            if ($filter["source_data"] == 2) {
                //区域服务商
                $list = $list->with(["regionservice" => function ($query) {
                    $query->withField('id,name');
                }]);
            }
            if ($filter["source_data"] == 3) {
                //卡经销商
                $list = $list->with(["dealer" => function ($query) {
                    $query->withField('id,name');
                }]);
            }
            if ($filter["source_data"] == 4) {
                //分销商
                $list = $list->with(["distributor" => function ($query) {
                    $query->withField('id,name');
                }]);
            }
        }
        $list = $list->where($where)
            ->order($sort, $order)
            ->paginate($limit);
        $result = ['total' => $list->total(), 'rows' => $list->items(), "source_data" => $source_data];
        return json($result);
    }


    /**
     * 审核
     * */
    public function operation($id)
    {
        $param = $this->request->param();
        $row = $this->model->get($id);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        if($row["status"]!=0) $this->error("已审核");
        $param["operate_time"] = time();
        if ($param["status"] == 1) $param["remark"] = '';
        if ($row["source_data"] == 1) {
            if ($row["is_trila"] == 1) {
                $store = \app\common\model\Merchantuser::field("money,openid")->where(["is_trila" => 1])->find();
                $openid=$store["openid"]??'';
            } else {
                $store = Merchant::field("money")->where(["id" => $row["store_id"]])->find();
                $openid = \app\common\model\Merchantuser::field("openid")->where(["merchant_id" => $row["store_id"], "is_super" => '1'])->find();
                $openid = $openid["openid"] ?? '';
            }
        }
        if ($row["source_data"] == 2) {
            $store = \app\common\model\Regionservice::field("id,money")->where(["id" => $row["store_id"]])->find();
            $openid = \app\common\model\Regionserviceuser::field("openid")->where(["regionservice_id" => $row["store_id"], "is_super" => '1'])->find();
            $openid = $openid["openid"] ?? '';
        }
        if ($row["source_data"] == 3) {
            $store = Dealer::field("money,openid")->where(["id" => $row["user_id"]])->find();
            $openid=$store["openid"]??'';
        }
        if ($row["source_data"] == 4) {
            $store = \app\common\model\Distributor::field("money,openid")->where(["id" => $row["user_id"]])->find();
            $openid=$store["openid"]??'';
        }
        //$openid= "onyHr51FcBsH4Mi0g9vrSraDjfzU";
        if ($param["status"] == 1 && empty($openid)) $this->error("请先到微信公众平台获取openid");
        if ($param["status"] == 2) {
            //驳回
            Db::startTrans();
            try {
                if (!empty($store)) {
                    $store->save(["money" => $store["money"] + $row["price"]]);
                }
                if ($row["source_data"] == 2) {
                    $order = Order::where(["regionservice_id" => $store["id"], "regionservice_status" => '1'])
                        ->whereIn("status", ['1', '3'])
                        ->whereIn("type_data", ['0', '3']);
                    $list = Washlog::where(["regionservice_id" => $store["id"], "regionservice_status" => '1'])
                        ->where("type_data <> '2'");
                    if (!empty($row["start_time"])) {
                        $list = $list->whereTime('createtime', 'between', [strtotime($row["start_time"] . "00:00:00"), strtotime($row["end_time"] . "23:59:59")]);
                        $order = $order->whereTime('createtime', 'between', [strtotime($row["start_time"] . "00:00:00"), strtotime($row["end_time"] . "23:59:59")]);
                    }
                    $list = $list->update([
                        "regionservice_status" => '0'
                    ]);
                    $order = $order->update([
                        "regionservice_status" => '0'
                    ]);
                }
                $result = $row->allowField(true)->save($param);
                Db::commit();
            } catch (Exception $e) {
                Db::rollback();
                $this->error($e->getMessage());
            }
        } else {
            if(!empty($row["trans_no"])){
                $trans_no=$row["trans_no"];
            }else{
                $trans_no=$this->model->getTrans_no(20);
                $param["trans_no"]=$trans_no;
            }
            $data = [
                "trans_no" => $trans_no,
                "openid" => $openid,
                "amount" => 0.01,//$row["actual_receipt"],
                "desc" => "提现",
            ];
            //请求打款
            $wxpay = new Wxpay();
            $pay = $wxpay->WechatTransfer($data);
            if (!isset($pay["code"])) {
                $result = $row->allowField(true)->save($param);
                $this->success("成功");
            } else {
                $this->error($pay["message"]);
            }
        }
        if ($result !== false) {
            $this->success();
        } else {
            $this->error(__('No rows were updated'));
        }
    }
}
